package org.mc.domainservice;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.mc.bean.Account;
import org.mc.common.util.JSONUtils;
import org.mc.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Optional;

/**
 * Created by luoxf on 2018/5/29.
 */
@Service
@Slf4j
public class AccountDomainService {

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public Account save(Account account) {
        stringRedisTemplate.opsForValue().set("test", "测试", 60L);

        return accountRepository.save(account);
    }

    public Account getByid(Long id) {
        Optional<Account> optionalAccount = accountRepository.findById(id);
        Account account = null;
        if (optionalAccount.isPresent()) {
            account = optionalAccount.get();
        }


        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(id + "");
        Iterable<Account> iterable = accountRepository.search(builder);
        Iterator<Account> iterator = iterable.iterator();
        while (iterator.hasNext()) {
            log.info(iterator.next().toString());
        }
        return account;
    }

    @Cacheable(value = "listPage", cacheManager = "ex")
    public Page listPage(int pageIndex, int pageSize) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        PageRequest pageRequest = PageRequest.of(pageIndex, pageSize, sort);
        Page page = accountRepository.findAll(pageRequest);
        log.info("page:" + JSONUtils.toJson(page));
        return page;
    }
}
